package cn.edu.cqytxy.util;

import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author yinjw
 */
public class JdbcUtils {

    /**
     * 数据库连接串
     */
    private static final String URL = "jdbc:mysql://localhost:3306/warplane-system?allowMultiQueries=true";
    /**
     * 用户名
     */
    private static final String USERNAME = "root";

    /**
     * 密码
     */
    private static final String PASSWORD = "1234";

    private static DataSource dataSource;

    static {
        dataSource = new DruidDataSource();
        DruidDataSource druidDataSource = (DruidDataSource) dataSource;
        // 设置连接属性
        druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        druidDataSource.setUrl(URL);
        druidDataSource.setUsername(USERNAME);
        druidDataSource.setPassword(PASSWORD);

        // 初始连接数
        druidDataSource.setInitialSize(5);

        // 最大连接数
        druidDataSource.setMaxActive(10);

        // 最小空闲数
        druidDataSource.setMinIdle(5);

        // 获取连接时最大等待时间
        druidDataSource.setMaxWait(60000);

        druidDataSource.setValidationQuery("select 1");
    }

    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }
    }
}
